//
// Created by 86155 on 2025/4/16.
//

#include "FeFrameLowering.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "MCTargetDesc/FeMCTargetDesc.h"
#include "Fe.h"
#include "FeSubtarget.h"

#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"

using namespace llvm;
//计算栈大小
uint64_t FeFrameLowering::computeStateSize(MachineFunction &MF) const {
  uint64_t STACKSIZE = MF.getFrameInfo().getStackSize();
  if (getStackAlignment() > 0) {
    STACKSIZE = ROUND_UP(STACKSIZE, getStackAlignment());//对齐处理
  }
  return STACKSIZE;
}

//前序
void FeFrameLowering::emitPrologue(MachineFunction &MF,
                                    MachineBasicBlock &MBB) const {
//  MachineBasicBlock::iterator MBBI = MBB.begin();  //插入位置
//
//  const TargetInstrInfo &TII = *STI.getInstrInfo();
//
//  int STACKSIZE = computeStateSize(MF);
//
//  if (STACKSIZE == 0) {
//    return;
//  }
//
//  //构建指令
//  DebugLoc DL = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
//  BuildMI(MBB, MBBI, DL, TII.get(Fe::ADDI), Fe::SP)
//      .addReg(Fe::SP)
//      .addImm(-STACKSIZE)
//      .setMIFlag(MachineInstr::FrameSetup);
}
//尾声
void FeFrameLowering::emitEpilogue(MachineFunction &MF,
                                    MachineBasicBlock &MBB) const {
//  MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
//
//  const TargetInstrInfo &TII = *STI.getInstrInfo();
//
//  int STACKSIZE = computeStateSize(MF);
//
//  if (STACKSIZE == 0) {
//    return;
//  }
//
//  DebugLoc DL = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
//  BuildMI(MBB, MBBI, DL, TII.get(Fe::ADDI), Fe::SP)
//      .addReg(Fe::SP)
//      .addImm(STACKSIZE)
//      .setMIFlag(MachineInstr::FrameDestroy);
}

void FeFrameLowering::determineCalleeSaves(MachineFunction &MF, BitVector &SavedRegs, RegScavenger *RS) const {
//  TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
//  if (MF.getFrameInfo().hasCalls()) {
//    SavedRegs.set(Fe::RA);
//  }
}

bool FeFrameLowering::hasFP(const MachineFunction &MF) const {
  return false;
}